#!/usr/bin/env python
#
# Copyright (C) 2007 Jason Kivlighn
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, #USA.

import sqlite3
import sys
import time
import os
import random

import fetch_lastfm as lastfm

def fetch_random_neighbors(seeds):
  while True:
    user = random.choice(seeds)
    db_name = "lastfm-%s.db" % user
    init_db = not os.path.exists(db_name)
    db_conn = sqlite3.connect(db_name)
  
    if init_db:
      print "Initializing database: %s" % db_name
      db_c = db_conn.cursor()
      db_c.execute('''CREATE TABLE artists (begin INT, end INT, artist TEXT, playcount INT)''')
      db_c.execute('''CREATE TABLE tracks (begin INT, end INT, track TEXT, playcount INT)''')
      db_c.execute('''CREATE TABLE albums (begin INT, end INT, album TEXT, playcount INT)''')
      last_week = None
    else:
      db_c = db_conn.cursor()
      db_c.execute('''SELECT MAX(begin) FROM artists''')
      last_week, = db_c.fetchone()
      if last_week:
        print "Updating from", time.strftime("%b %d, %Y",time.gmtime(last_week+7*24*60*60))
        
    try:
      lastfm.write_weekly_user_data(db_conn,user,last_week)
    except:
      os.unlink(db_name)
      print "Failed:",user
    else:
      db_conn.commit()
      db_conn.close()
    
    try:
      seeds = lastfm.fetch_neighbors(user)
    except:
      #oh well, let's just pass and let another user from this same list be chosen
      #it'll probably work next time around
      pass

if __name__ == "__main__":
  if len(sys.argv) < 2:
    print "Usage: ./lastfm.py <user>"
    sys.exit(1)
  user = sys.argv[1]
  
  fetch_random_neighbors(lastfm.fetch_neighbors(user))
